package com.mbl.base.config.mybatis_plus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mbl.base.config.security.SecurityUser;
import com.mbl.base.core.utils.UtilSecurity;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 字段填充器
 */
@Component
public class MybatisPlusObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        final LocalDateTime now = LocalDateTime.now();
        if(isNull("createTime", metaObject)) {
            setInsertFieldValByName("createTime",now,metaObject);
        }
        if(isNull("createUser", metaObject)) {
            setInsertFieldValByName("createUser",getUserId(),metaObject);
        }
        if(isNull("updateTime", metaObject)) {
            setInsertFieldValByName("updateTime",now,metaObject);
        }
        if(isNull("updateUser", metaObject)) {
            setInsertFieldValByName("updateUser",getUserId(),metaObject);
        }
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        final LocalDateTime now = LocalDateTime.now();
        if(isNull("updateTime", metaObject)) {
            setUpdateFieldValByName("updateTime",now,metaObject);
        }
        if(isNull("updateUser", metaObject)) {
            setUpdateFieldValByName("updateUser",getUserId(),metaObject);
        }
    }

    private boolean isNull(String filedName, MetaObject metaObject){
        final Object fieldValByName = getFieldValByName(filedName, metaObject);
        return fieldValByName == null;
    }



    /**
     * 获取userId 供该类使用
     * @return
     */
    private Long getUserId(){
        final SecurityUser securityUser = UtilSecurity.getUser();
        Long id = -999l;
        if(securityUser != null){
            id = securityUser.getId();
        }
        return id;
    }
}
